<?php

namespace App\Services;

use Illuminate\Support\Facades\Response as FacadesResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use UtilsHelper;
use User;
use Log;

class UserService extends BaseService
{
	public function checkUser($post)
	{
			$union_id  = $post['union_id'];
			$platform  = $post['platform'];
			$wx_openid = isset($post['wx_openid']) ? $post['wx_openid'] : null;
			$user = User::getByUnionId($union_id, $platform);
//			var_dump($union_id);
//			var_dump($platform);
//			dd($user);

			if(empty($user)) $user = User::where('wx_openid',$post['wx_openid'])->first();				
			if(!$user){
				$response = FacadesResponse::json (
					array (
						"status_code" => 400,
						"success_messages" => array("用户不存在"),
						"data" => [],
					),
					200
				);
				return $response;
			}
			
			
			/**
			 * 存储wx_openid
			 */
			if($wx_openid){
				$user->wx_openid = $wx_openid;
				$user->save();
			}
			Auth::login($user);
			$token = $this->getNewToken();
			$response = FacadesResponse::json (
				array (
					"status_code" => 200,
					"success_messages" => array("用户已经成功登录。"),
					"data" => $this->getAuthUserData(),
					"token" => $token,
				),
				200,
				["Authorization" => "bearer " . $token]
			);
			return $response;
	}

	public function getNewToken() {
		// 获取新的 jwt token
		$row = User::find(Auth::user()->id);
		$token = JWTAuth::fromUser($row);

		DB::table('user')->where('id', '=',$row->id )->update(array(
			'last_login' => date("Y-m-d H:i:s"),
			'login_token' => $token
		));

		return $token;
	}

	public function getAuthUserData() {
		$whitelist = array(
			'id',
			'username',
			'easemob_password',
			'email',
			'avatar',
			'phone',
			'score',
			'likes_count',
			'collects_count',
			'status',
			'is_verified',
			'realname',
			'province',
			'city',
			'district',
			'address',
			'nikname',
			'sex',
			'follows_count',
			'signature',
			'user_group_id',
			'wx_openid'
		);

		$whitelist = array_flip($whitelist);
		$userArr = Auth::user()->toArray();
		$userArr['easemob_password'] = Auth::user()->password;
		if (!isset($userArr['avatar'])) {
			$userArr['avatar'] = "";
		}
		$userArr['avatar'] = UtilsHelper::getImage($userArr['avatar'], "img/dfimg.png");
		$userArr = array_intersect_key($userArr, $whitelist);
		return $userArr;
	}
}